package com.hevs.samplewebapp.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.codehaus.jackson.map.ObjectMapper;

import com.google.appengine.api.datastore.Key;
import com.hevs.samplewebapp.server.entities.InternalMessage;
import com.hevs.samplewebapp.server.entities.User;
import com.hevs.samplewebapp.server.json.ObjectMapperFactory;
import com.hevs.samplewebapp.server.service.InternalMessageService;
import com.hevs.samplewebapp.server.service.UserService;

public class MessagingServlet extends SessionAuthHttpServlet{

	/**
	 * @author Arnaud Durand
	 */
	private static final long serialVersionUID = -8465617347860486644L;

	public static InternalMessageService internalMessageService;
	{
		internalMessageService = new InternalMessageService();
	};
	
	public static UserService userService;
	{
		userService = new UserService();
	};
	
	public MessagingServlet() {
		super(1);
	}
	
	@Override
	protected void doSecureGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		HttpSession session = req.getSession(false);
		User user = new User();
		user.setKey((Key) session.getAttribute("userKey"));

		List<InternalMessage> mails;

		
		mails = internalMessageService.getAllMessages(user);
		// System.out.println(medicalRecordDAO.getAll(aimUser));

		ObjectMapper mapper = ObjectMapperFactory.get();

		resp.setContentType("application/json");
		PrintWriter writer = resp.getWriter();
		writer.write(mapper.writeValueAsString(mails));

		writer.flush();
		
	}
	
	@Override
	protected void doSecureDelete(HttpServletRequest req,
			HttpServletResponse resp) throws ServletException, IOException {

		
		// ObjectMapper mapper = new ObjectMapper(); // can reuse, share
		// globall
		BufferedReader reader = req.getReader();
		StringBuilder sb = new StringBuilder();
		String line = reader.readLine();
		while (line != null) {
			sb.append(line + "\n");
			line = reader.readLine();
		}
		reader.close();
		System.out.println(sb.toString());

		ObjectMapper mapper = ObjectMapperFactory.get();
		InternalMessage mail = mapper.readValue(sb.toString(), InternalMessage.class);

		// throw Error 400
		if (mail == null || mail.getKey() == null) {
			resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
			return;
		}

		
		internalMessageService.removeMessage(mail);

	}
	
	@Override
	protected void doSecurePost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		HttpSession session = req.getSession(false);
		User sender = userService.getUser((Key) session.getAttribute("userKey"));
		
		User receiver= userService.getUserByMail(
				req.getPathInfo().replace("/", ""));
		
		BufferedReader reader = req.getReader();
		StringBuilder sb = new StringBuilder();
		String line = reader.readLine();
		while (line != null) {
			sb.append(line + "\n");
			line = reader.readLine();
		}
		reader.close();
		System.out.println(sb.toString());

		ObjectMapper mapper = ObjectMapperFactory.get();
		InternalMessage mail = mapper.readValue(sb.toString(),
				InternalMessage.class);

		mail.setSenderEmail(sender.getEmail());
		mail.setSenderFirstName(sender.getFirstName());
		mail.setSenderLastName(sender.getLastName());
		
		internalMessageService.sendMessage(sender,receiver,mail);
	}

	
	
}
